package crypto.symmetric;

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class AsymmetricTest {
	public static void main(String[] args) {
		String input = "hello, welcome you do cao tri";
		System.out.println("Input Text: " + input);
		PublicKey publicKey;
		PrivateKey privateKey;
		byte[] encryptedOutput;
		byte[] decryptedOutput;

		try {
			KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
			gen.initialize(2048, new SecureRandom());
			KeyPair key = gen.generateKeyPair();
			// genkey

			publicKey = key.getPublic();
			privateKey = key.getPrivate();

			// ma hoa voi public KEY

			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			encryptedOutput = cipher.doFinal(input.getBytes());
			System.out
					.println("encrypted text: " + new String(encryptedOutput));

			// giai ma
			cipher = cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			decryptedOutput = cipher.doFinal(encryptedOutput);

			System.out
					.println("decrypted text: " + new String(decryptedOutput));

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
	}

}
